// login.js
document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');

    loginForm.addEventListener('submit', async function(e) {
        e.preventDefault();

        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        // 构造请求数据
        const requestData = {
            username: username,
            password: password
        };

        try {
            // 发送登录请求
            const response = await fetch('/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            });

            // 检查响应状态
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP ${response.status}: ${errorText || response.statusText}`);
            }

            const data = await response.json();

            if (data.user_id) {
                alert('登录成功！');
                // 存储用户信息
                localStorage.setItem('user_id', data.user_id);
                localStorage.setItem('username', data.username);
                window.location.href = 'note.html';
            } else {
                alert('登录失败：' + (data.detail || data.message || '未知错误'));
            }
        } catch (error) {
            console.error('登录错误详情:', error);

            if (error instanceof TypeError) {
                // 网络错误
                if (error.message.includes('Failed to fetch')) {
                    alert('网络错误：无法连接到服务器，请确保后端服务正在运行');
                } else {
                    alert('网络错误：' + error.message);
                }
            } else if (error.message.startsWith('HTTP')) {
                // HTTP错误
                alert('服务器返回错误: ' + error.message);
            } else {
                // 其他错误
                alert('登录过程中出现错误，请稍后重试\n详细信息：' + error.message);
            }
        }
    });

    // 注册链接跳转
    document.getElementById('registerLink').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'register.html';
    });
});
